package com.appspot.mypartymanager.mbean;

import java.util.ResourceBundle;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@ManagedBean(name = "loginBean")
@RequestScoped
public class LoginBean {
	
	private User user;
	
	private String url;
	
	private UserService userService;
	
	private ResourceBundle msg =  ResourceBundle.getBundle("com.appspot.mypartymanager.resources.messages");
	
	public LoginBean() {
		
		userService = UserServiceFactory.getUserService();
		user = userService.getCurrentUser();
		
	}
	
	public String getUrl() {
	
		
		
		
		ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
	    HttpServletRequest request = (HttpServletRequest) ctx.getRequest();
	    
	    if(user != null) {
			url = "/MyPartyManager?action=logout&requestURI=" + "/index.html";
		} else {
			url = "/MyPartyManager?action=login&requestURI=" + request.getRequestURI();
		}
		
//		if (user != null) {
//			
//			url = userService.createLogoutURL(response.encodeUrl(request.getRequestURI()));
//			
//		} else {
//			url = userService.createLoginURL(response.encodeUrl(request.getRequestURI()));
//			 
//		}
		
		return url;		
	}
	
	
	public User getUser() {
		return user;
	}
	
	public void setUser(User user) {
		this.user = user;
	}
	
	public String getOutputLinkText() {
		
		if (user != null) {
			return msg.getString("app.login.signout");
		}
		else {
			return msg.getString("app.login.signin");
		}
			
	}
	
	public String getSignMessage() {
		
		if (user != null) {
			return user.getEmail();
		}
		else {
			return msg.getString("app.login.welcome") ;
			
		}
			
	}
	
	public String getMyParties() {
		
		if (user != null) {
			return msg.getString("entity.party.list");
		}
		else {
			return "";
			
		}
		
	}
	
}
